from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView,GenericAPIView,ListCreateAPIView
from  rest_framework.permissions import IsAdminUser

from meiduo_admin.serializers.users import AdminAuthSerializer, UserSerializer
from users.models import User

# POST /meiduo_admin/authorizations/
class AdminAuthView(APIView):
    # 管理员登录：
    def post(self, request):

        # 1. 获取参数并进行校验(参数完整性，用户名和密码正确)
        serializer = AdminAuthSerializer(data=request.data)

        serializer.is_valid(raise_exception=True)

        # 2. 服务器创建一个jwt token，保存登录用户身份信息(create)
        serializer.save()

        # 3. 返回响应，登录成功
        return Response(serializer.data, status=status.HTTP_201_CREATED)


# GET /meiduo_admin/users/?keyword=<搜索内容>&page=<页码>&pagesize=<页容量>
class UserInfoView(ListCreateAPIView):
    # 查询用户
    permission_classes = [IsAdminUser]
    # 代码优化
    serializer_class = UserSerializer

    # 获取查询字符窜中的查询参数
    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword is None or keyword == '':
            user = User.objects.filter(is_staff=False)
        else:
            user = User.objects.filter(is_staff=False,username__contains=keyword)
        return user

    # def get(self,request):
    #     keyword = request.query_params.get('keyword')
    #     if keyword is None or keyword == '':
    #         user = User.objects.filter(is_staff=False)
    #     else:
    #         user = User.objects.filter(is_staff=False,username__contains=keyword)
    #     serializer = UserSerializer(user, many=True)
    #
    #     return Response(serializer.data)
    # APIView 创建用户
    # def post(self,request):
    #     queryset = request.data
    #     serializer = UserSerializer(data=queryset)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()
    #     return Response(serializer.validated_data)









